package com.zhengtoudai.ui.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhengtoudai.R;
import com.zhengtoudai.base.App;
import com.zhengtoudai.base.BaseActivity;
import com.zhengtoudai.global.Config;
import com.zhengtoudai.http.HttpUtil;
import com.zhengtoudai.injector.component.DaggerActivityComponent;
import com.zhengtoudai.injector.module.ActivityModule;
import com.zhengtoudai.ui.adapter.RedPacketAdapter;
import com.zhengtoudai.ui.bean.BorrowDetails;
import com.zhengtoudai.ui.presenter.BorrowDetailPresenterImpl;
import com.zhengtoudai.ui.presenter.ShengTenpayPresenterImpl;
import com.zhengtoudai.ui.view.BorrowDetailView;
import com.zhengtoudai.ui.view.ShengTenpeyView;
import com.zhengtoudai.util.AbToastUtil;
import com.zhengtoudai.util.CashierInputFilter;
import com.zhengtoudai.util.Tool;
import com.zhengtoudai.view.MyProgressBar;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 投资界面
 */
public class InvestmentActivity extends BaseActivity implements BorrowDetailView, ShengTenpeyView {


    @Bind(R.id.iv_img)
    ImageView mIvImg;
    @Bind(R.id.tv_year_rate)
    TextView mTvYearRate;
    @Bind(R.id.tv_borrow_money)
    TextView mTvBorrowMoney;
    @Bind(R.id.tv_time_limit)
    TextView mTvTimeLimit;
    @Bind(R.id.tv_surplus_money)
    TextView mTvSurplusMoney;
    @Bind(R.id.my_progressbar)
    MyProgressBar mMyProgressbar;
    @Bind(R.id.tv_available_balance)
    TextView mTvAvailableBalance;
    @Bind(R.id.btn_recharge)
    Button mBtnRecharge;
    @Bind(R.id.edt_invest_money)
    EditText mEdtInvestMoney;
    @Bind(R.id.btn_investment)
    Button mBtnInvestment;
    @Bind(R.id.tv_project_title)
    TextView mTvProjectTitle;
    @Bind(R.id.tv_investment_record)
    TextView mTvInvestmentRecord;
    @Bind(R.id.tv_project_detail)
    TextView mTvProjectDetail;
    @Bind(R.id.activity_investment)
    LinearLayout mActivityInvestment;

    @Inject
    BorrowDetailPresenterImpl mDetailPresenter;
    @Inject
    ShengTenpayPresenterImpl mTenpayPresenter;
    @Bind(R.id.tv_day)
    TextView mTvDay;
    @Bind(R.id.tv_hour)
    TextView mTvHour;
    @Bind(R.id.tv_minute)
    TextView mTvMinute;
    @Bind(R.id.tv_second)
    TextView mTvSecond;
    @Bind(R.id.spinner)
    Spinner mSpinner;
    private String borrowEId;
    private String redId;
    private String borrowStatus;
    private Subscription mSubscription;

    @Inject
    LayoutInflater mInflater;
    private RedPacketAdapter mAdapter;

    private BorrowDetails result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_investment);
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        titleUtil.setTitle("理财");
    }

    @Override
    protected void initView() {
        borrowEId = getIntent().getStringExtra("borrowEId");
        borrowStatus = getIntent().getStringExtra("borrowStatus");
        DaggerActivityComponent.builder().appComponent(App.mApp.getAppComponent())
                .activityModule(new ActivityModule(this))
                .build()
                .inject(this);
        mDetailPresenter.attachView(this);
        mTenpayPresenter.attachView(this);
        //mDetailPresenter.borrowDetail(borrowEId);
        mEdtInvestMoney.setFilters(new InputFilter[]{new CashierInputFilter()});
        mEdtInvestMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)||Double.parseDouble(s.toString())<mAdapter.getData().get(mAdapter.getCheckPosition()).getMin_money()){
                    mAdapter.setCheckPosition(0);
                    mSpinner.setSelection(0);
                    redId=null;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mAdapter=new RedPacketAdapter(mInflater,context);
        mSpinner.setAdapter(mAdapter);
        mSpinner.setSelection(mAdapter.getCheckPosition());
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position>0){
                    String money=mEdtInvestMoney.getText().toString();
                    if (TextUtils.isEmpty(money)){
                        AbToastUtil.showToast(context,"请输入投资金额");
                        mSpinner.setSelection(mAdapter.getCheckPosition());
                    }else if (Double.parseDouble(money)<mAdapter.getData().get(position).getMin_money()){
                        AbToastUtil.showToast(context,"投资金额不满足红包使用条件");
                        mSpinner.setSelection(mAdapter.getCheckPosition());
                    }else {
                        redId=mAdapter.getData().get(position).getId();
                        mAdapter.setCheckPosition(position);
                    }
                }else{
                    redId=null;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDetailPresenter.detachView();
        mTenpayPresenter.detachView();
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }

    @OnClick({R.id.btn_recharge, R.id.btn_investment, R.id.tv_investment_record, R.id.tv_project_detail})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        mEdtInvestMoney.setError(null);
        switch (view.getId()) {
            case R.id.btn_recharge:
                if (result!=null){
                    if (result.getRealnameStatus().equals("2")){
                        startActivity(RechargeActivity.class);
                    }else{
                        startActivity(RealNameCertificationActivity.class);
                        AbToastUtil.showToast(context,"请先绑定盛付通");
                    }
                }else{
                    AbToastUtil.showToast(context,"正在获取详情...");
                    mDetailPresenter.borrowDetail(borrowEId);
                }
                break;
            case R.id.btn_investment:
                String tenderAmount = mEdtInvestMoney.getText().toString();
                if (TextUtils.isEmpty(tenderAmount)) {
                    mEdtInvestMoney.setError("请输入投标金额");
                } else {
                    Map<String, String> params = new HashMap<>();
                    //params.put("borrowEid", "[j]GnsDYMWrKk[d]");
                    params.put("borrowEid", borrowEId);
                    params.put("tenderAmount", tenderAmount);
                    if (redId != null) {
                        params.put("redUserId", redId);
                    }
                    mTenpayPresenter.postShengTenpay("appBorrowLoggedCorrelation/saveTender.app", params);
                }

                break;
            case R.id.tv_investment_record:
                Bundle record = new Bundle();
                record.putString("type", "borrowId");
                record.putString("id", borrowEId);
                startActivity(record, InvestmentRecordActivity.class);
                break;
            case R.id.tv_project_detail:
                Bundle bundle = new Bundle();
                bundle.putString("title", "项目详情");
                bundle.putString("url", Config.BASE_URL + "web/borrow/borrowInfo/" + borrowEId + ".do");
                startActivity(bundle, WebViewActivity.class);
                break;
        }
    }

    @Override
    public void showDetailDialog() {
        status.showLoading();
        //showProgressDialog("正在获取详情...");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (App.mApp.hasLogin()){
            mDetailPresenter.borrowDetail(borrowEId);
        }else{
            startActivity(LoginActivity.class);
            AbToastUtil.showToast(context,"请先登录");
            finish();
        }
    }

    @Override
    public void onDetailResult(BorrowDetails result) {
        this.result=result;
        BorrowDetails.NewListBorrowEntity borrow = result.getNewListBorrow().get(0);
        Glide.with(this).load(Config.URL+borrow.getImgUrl())
                .error(R.mipmap.xq001)
                .into(mIvImg);
        mTvProjectTitle.setText(borrow.getBorrowTitle());
        mTvYearRate.setText(borrow.getRate() + "%");
        mTvBorrowMoney.setText("¥" + borrow.getBorrowSum());
        mTvTimeLimit.setText(borrow.getBorrowTimeLimit() + borrow.getIsDay());
        mTvSurplusMoney.setText("¥" + borrow.getLeftAllowTender());
        countDown(borrow.getAllowTenderTime() - borrow.getNowDate());
        mMyProgressbar.setProgress((int) Math.round(borrow.getPercentage()));
        mTvAvailableBalance.setText("¥" + result.getAvailableInvestMoney());

        if (result.getRedList()!=null||result.getRedList().size()>0){
            mAdapter.addData(result.getRedList());
        }

        String status=borrowStatus;
        if (status==null){ //首页进来没有传，设置个默认的值
            status="6";
        }
        int backgroundResId;
        String btnText;
       if (status.equals("8")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="满标审核";
        }else if (status.equals("9")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="审核通过";
        }else if (status.equals("10")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="审核未通过";
        }else if (status.equals("11")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="还款中";
        }else if (status.equals("12")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="还款完成";
        }else if (status.equals("13")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="逾期";
        }else if (status.equals("14")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="自己取消";
        }else if (status.equals("15")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="平台取消";
        }else if (status.equals("16")){
            backgroundResId=R.drawable.shape_gray_button;
            btnText="已流标";
        }else{
            backgroundResId=R.drawable.shape_red_button;
            btnText="立即投资"; //if (status.equals("6"))
       }
        if (btnText.equals("立即投资")){
            mBtnInvestment.setClickable(true);
        }else{
            mBtnInvestment.setClickable(false);
        }
        mBtnInvestment.setBackgroundResource(backgroundResId);
        mBtnInvestment.setText(btnText);

    }

    private void countDown(final long countTime) {
        mSubscription = Observable.create(new Observable.OnSubscribe<Long>() {
            @Override
            public void call(Subscriber<? super Long> subscriber) {
                long count = countTime;
                while (count > 0&&mSubscription!=null&&!mSubscription.isUnsubscribed()) {
                    try {
                        count -= 1000;
                        subscriber.onNext(count);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        subscriber.onError(e);
                    }
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Func1<Long, Observable<String[]>>() {
                    @Override
                    public Observable<String[]> call(Long time) {
                        String[] times = new String[4];
                        time=time/1000; //转换成秒
                        long second=time%60;//剩余秒
                        time=(time-second)/60; //转换成分钟
                        long minute=time%60;//剩余分钟
                        time=(time-minute)/60;//转换成小时
                        long hour=time%24;//剩余小时
                        long day=(time-hour)/24;//剩余天
                        times[0] = day + "";
                        times[1] = hour + "";
                        times[2] = minute + "";
                        times[3] = second + "";
                        return Observable.just(times);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Action1<String[]>() {
                    @Override
                    public void call(String[] strs) {
                        mTvDay.setText(strs[0]);
                        mTvHour.setText(strs[1]);
                        mTvMinute.setText(strs[2]);
                        mTvSecond.setText(strs[3]);
                    }
                });

    }

    @Override
    public void dismissDetailDialog() {
        status.removeView();
    }

    @Override
    public void showDialog() {
        showProgressDialog("正在跳转中...");
    }

    @Override
    public void onFailure(Throwable e) {
        HttpUtil.disposeOnFailure(context, e);
    }

    @Override
    public void onResult(String html) {
        Bundle bundle = new Bundle();
        bundle.putString("title", "盛付通");
        bundle.putString("html", html);
        startActivity(bundle, WebViewActivity.class);
    }

    @Override
    public void dismissDialog() {
        dismissProgressDialog();
    }

}
